import axios from "axios";
import { connectSocket } from "@/utils/socket";
import { aesEncrypt, MD5 } from "~/utils/encrypt";
import Cookies from "js-cookie";

let isOutTimer = null;

const onIsOut = () => {
    const userStore = useUserStore();
    userStore.CLEAR_USERINFO();
    userStore.token = "";

    if (process.client) {
        if (isOutTimer) clearTimeout(isOutTimer);
        connectSocket();
        userStore.token = "";

        if (process.env.NODE_ENV === "development") {
            Cookies.remove("ykj_token", { path: "/", domain: 'localhost' });
        } else {
            Cookies.remove("ykj_token", { path: "/", domain: '.ykjhr.com' });
        }
        isOutTimer = setTimeout(() => {
            Message().warning("帐号已经在其他地方登录，请重新登录。");
        }, 500);
    }
};

const GetHeader = () => {
    const timeStamp = Date.now();
    const randomStr = generateRandomString(8);
    const token = "HuaRui-three-dimensional";
    const headers = {
        timeStamp,
        randomStr,
        signature: MD5(aesEncrypt(randomStr + timeStamp + token)).toUpperCase(),
    };
    return headers;
};

export const GET = async (url, options = {}) => {
    if (process.client) {
        await nextTick();
    }
    const userStore = useUserStore();
    const { data } = await useFetch(url, {
        key: MD5(url + JSON.stringify(options.query)),
        method: "get",
        headers: {
            token: userStore.token || "",
            ...GetHeader(),
        },
        watch: false,
        onResponse({ request, response, options }) {
            if (response.headers.get("tokenOut")) {
                // 当前登录凭证过期
                onIsOut();
            }
        },
        ...options,
    });
    return data.value;
};

export const POST = async (url, options = {}) => {
    if (process.client) {
        await nextTick();
    }
    const userStore = useUserStore();
    const pageStore = usePageStore();
    if (pageStore.isMobile) {
        const res = await axios({
            method: "post",
            url,
            headers: {
                "Content-Type": "application/json",
                token: userStore.token || "",
                ...GetHeader(),
            },
            withCredentials: true,
            data: options?.body,
        });
        if (res.headers.get("tokenOut")) {
            onIsOut();
        }
        return res.data;
    } else {
        const { data } = await useFetch(url, {
            key: MD5(url + JSON.stringify(options.body)),
            method: "post",
            headers: {
                "Content-Type": "application/json",
                token: userStore.token || "",
                ...GetHeader(),
                'Cache-Control': 'no-cache',
            },
            watch: false,
            onResponse({ request, response, options }) {
                if (response.headers.get("tokenOut")) {
                    // 当前登录凭证过期
                    onIsOut();
                }
            },
            ...options,
        });
        return data.value;
    }
};

export const UPLOAD = async (url, options) => {
    if (process.client) {
        await nextTick();
    }
    const userStore = useUserStore();
    const { data } = await useFetch(url, {
        // key: uuid(),
        method: "post",
        headers: {
            token: userStore.token || "",
            ...GetHeader(),
        },
        watch: false,
        onResponse({ request, response, options }) {
            if (response.headers.get("tokenOut")) {
                // 当前登录凭证过期
                onIsOut();
            }
        },
        ...options,
    });
    return data.value;
};

export const DOWNLOAD = async (url, options = {}) => {
    const userStore = useUserStore();
    const res = await axios({
        method: "get",
        url,
        headers: {
            token: userStore.token,
        },
        responseType: "blob",
        ...options,
    });
    return res.data;
};
